package vip.ola.manage.order.ctrl;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import vip.ola.core.common.constant.Constant;
import vip.ola.core.common.constant.PayConstant;
import vip.ola.core.common.domain.PayPageRes;
import vip.ola.core.common.domain.PayResponse;
import vip.ola.core.common.util.DateUtil;
import vip.ola.core.common.util.MyLog;
import vip.ola.core.entity.TransOrder;
import vip.ola.manage.common.ctrl.BaseController;
import vip.ola.manage.common.service.RpcCommonService;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * @author: dingzhiwei
 * @date: 17/12/6
 * @description:
 */
@RestController
@RequestMapping(Constant.MGR_CONTROLLER_ROOT_PATH + "/trans_order")
public class TransOrderController extends BaseController {
    @Autowired
    private static final MyLog _log = MyLog.getLog(TransOrderController.class);
    @Autowired
    private RpcCommonService rpcCommonService;

    /**
     * 查询单条转账记录
     * @return
     */
    @RequestMapping("/get")
    @ResponseBody
    public ResponseEntity<?> get(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        String transOrderId = getStringRequired(param, "transOrderId");
        TransOrder transOrder = rpcCommonService.rpcTransOrderService.findByTransOrderId(transOrderId);
        return ResponseEntity.ok(PayResponse.buildSuccess(transOrder));
    }

    /**
     * 订单记录列表
     * @return
     */
    @RequestMapping("/list")
    @ResponseBody
    public ResponseEntity<?> list(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        TransOrder transOrder = getObject(param, TransOrder.class);
        // 订单起止时间
        Date createTimeStart = null;
        Date createTimeEnd = null;
        String createTimeStartStr = getString(param, "createTimeStart");
        if(StringUtils.isNotBlank(createTimeStartStr)) createTimeStart = DateUtil.str2date(createTimeStartStr);
        String createTimeEndStr = getString(param, "createTimeEnd");
        if(StringUtils.isNotBlank(createTimeEndStr)) createTimeEnd = DateUtil.str2date(createTimeEndStr);

        int count = rpcCommonService.rpcTransOrderService.count(transOrder, createTimeStart, createTimeEnd);
        if(count == 0) return ResponseEntity.ok(PayPageRes.buildSuccess());
        List<TransOrder> transOrderList = rpcCommonService.rpcTransOrderService.select((getPageIndex(param) -1) * getPageSize(param),
                getPageSize(param), transOrder, createTimeStart, createTimeEnd);
        return ResponseEntity.ok(PayPageRes.buildSuccess(transOrderList, count));
    }

    /**
     * 查询订单统计数据
     * @return
     */
    @RequestMapping("/count")
    @ResponseBody
    public ResponseEntity<?> count(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        String transOrderId = getString(param, "transOrderId");
        String mchTransNo = getString(param, "mchTransNo");
        Long mchId = getLong(param, "mchId");
        Integer status = getInteger(param, "status");
        String appId = getString(param, "appId");

        Long passageId = getLong(param, "passageId");

        // 订单起止时间
        String createTimeStartStr = getString(param, "createTimeStart");
        String createTimeEndStr = getString(param, "createTimeEnd");
        Map allMap = rpcCommonService.rpcTransOrderService.countNew4All(mchId, transOrderId, mchTransNo, createTimeStartStr, createTimeEndStr,status,appId,passageId);
        Map successMap = rpcCommonService.rpcTransOrderService.countNew4Success(mchId, transOrderId, mchTransNo, createTimeStartStr, createTimeEndStr,status,appId,passageId);
        Map allMerchantMap = rpcCommonService.rpcMchAccountService.countNewBalance(mchId,"",null);
        JSONObject obj = new JSONObject();
        obj.put("allTotalCount", allMap.get("totalCount"));                         // 所有订单数
        obj.put("allTotalAmount", allMap.get("totalAmount"));                       // 总金额
        obj.put("successTotalCount", successMap.get("totalCount"));                 // 成功订单数
        obj.put("successTotalAmount", successMap.get("totalAmount"));               // 成功金额
        obj.put("successTotalChannelCost", successMap.get("totalChannelCost"));     // 成功渠道成本
        obj.put("totalAgnetBalacne", allMerchantMap.get("agentpayBalanceCount"));     // 成功渠道成本
        return ResponseEntity.ok(PayResponse.buildSuccess(obj));
    }

    @RequestMapping("/deal")
    public ResponseEntity<?> deal(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);

        // 判断输入的超级密码是否正确
//        String password = getStringRequired(param, "superpassword");
//        if(!MGR_SUPER_PASSWORD.equals(password)) {
//            return ResponseEntity.ok(BizResponse.build(RetEnum.RET_MGR_SUPER_PASSWORD_NOT_MATCH));
//        }
        String remark = getString(param, "remark");
        String status = getStringRequired(param, "status");
        // 是否通知商户
        boolean isNotifyMch = false;
        // 修改订单状态

        String transOrderId = getStringRequired(param, "transOrderId");
        TransOrder transOrder = rpcCommonService.rpcTransOrderService.findByTransOrderId(transOrderId);
        if(transOrder.getStatus() == PayConstant.TRANS_STATUS_TRANING) { // 初始或支付中
            // 修改状态
            if ("2".equals(status)){
                int updateCount = rpcCommonService.rpcTransOrderService.updateStatus4Success(transOrderId);
                _log.info("[补单]userId={},payOrderId={},将支付中修改为支付成功,返回结果:{}", getUser().getId(), transOrder.getTransOrderId(), updateCount);
                if(updateCount == 1) isNotifyMch = true;
            }else if ("3".equals(status)){
                int updateCount = rpcCommonService.rpcTransOrderService.updateStatus4Fail(transOrderId,"999999",remark);
                _log.info("[补单]userId={},payOrderId={},将支付中修改为失败,返回结果:{}", getUser().getId(), transOrder.getTransOrderId(), updateCount);
                if(updateCount == 1) isNotifyMch = true;
            }

        }

        // 发送商户通知
        if(isNotifyMch) {
            rpcCommonService.rpcPayNotifyService.executeTransNotify(transOrderId);
        }

        return ResponseEntity.ok(PayResponse.buildSuccess(transOrder));

    }

    @RequestMapping("/batchDeal")
    public ResponseEntity<?> batchDeal(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        List<String>transOrderIds = param.getJSONArray("transOrderIds").toJavaList(String.class);
        String remark = getString(param, "remark");
        String status = getStringRequired(param, "status");
        // 修改订单状态
        if (transOrderIds != null && transOrderIds.size()>0){
            transOrderIds.forEach(transOrderId->{
                // 是否通知商户
                boolean isNotifyMch = false;
                TransOrder transOrder = rpcCommonService.rpcTransOrderService.findByTransOrderId(transOrderId);
                if(transOrder.getStatus() == PayConstant.TRANS_STATUS_TRANING) { // 初始或支付中
                    // 修改状态
                    if ("2".equals(status)){
                        int updateCount = rpcCommonService.rpcTransOrderService.updateStatus4Success(transOrderId);
                        _log.info("[补单]userId={},payOrderId={},将支付中修改为支付成功,返回结果:{}", getUser().getId(), transOrder.getTransOrderId(), updateCount);
                        if(updateCount == 1) isNotifyMch = true;
                    }else if ("3".equals(status)){
                        int updateCount = rpcCommonService.rpcTransOrderService.updateStatus4Fail(transOrderId,"999999",remark);
                        _log.info("[补单]userId={},payOrderId={},将支付中修改为失败,返回结果:{}", getUser().getId(), transOrder.getTransOrderId(), updateCount);
                        if(updateCount == 1) isNotifyMch = true;
                    }

                }

                // 发送商户通知
                if(isNotifyMch) {
                    rpcCommonService.rpcPayNotifyService.executeTransNotify(transOrderId);
                }
            });

        }
        return ResponseEntity.ok(PayResponse.buildSuccess());

    }

}
